package com.tiancheng.trade.payment.util.cmq;

import com.tiancheng.trade.commom.core.data.MessageBody;
import com.tiancheng.trade.commom.core.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Optional;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * cmq消息解析
 *
 * @author 李凯伦
 * @date 2022/5/31
 */
@Slf4j
@Component
public class MessageParsing {

    @Value(value = "${cmq.signKey}")
    private String signKey;


    /**
     * 解析消息
     * @param message
     * @return
     */
    public MessageBody get(String message) {
        Map<String, String> messageMap = JsonUtil.fromJson(message, Map.class);
        MessageBody msgBody = JsonUtil.fromJson(messageMap.get("msgBody"), MessageBody.class);

        // 验证签名
        SortedMap<String, Object> sortedMap = JsonUtil.fromJson(JsonUtil.toJsonString(msgBody), TreeMap.class);
        sortedMap.remove("sign");
        if(StringUtils.isEmpty(msgBody.getMessageType())) {
            sortedMap.remove("messageType");
        }
        Optional<String> sign = MessageSign.get(sortedMap, signKey);
        if(!sign.isPresent()) {
            throw new RuntimeException("消息内容签名失败");
        }
        if(!sign.get().equals(msgBody.getSign())) {
            throw new RuntimeException("消息内容签名不一致:" + sign.get());
        }

        return msgBody;
    }


    /**
     * 解析消息-队列
     * @param message
     * @return
     */
    public MessageBody getQueueBody(String message) {
        MessageBody msgBody = JsonUtil.fromJson(message, MessageBody.class);

        // 验证签名
        SortedMap<String, Object> sortedMap = JsonUtil.fromJson(JsonUtil.toJsonString(msgBody), TreeMap.class);
        sortedMap.remove("sign");
        if(StringUtils.isEmpty(msgBody.getMessageType())) {
            sortedMap.remove("messageType");
        }
        Optional<String> sign = MessageSign.get(sortedMap, signKey);
        if(!sign.isPresent()) {
            throw new RuntimeException("消息内容签名失败");
        }
        if(!sign.get().equals(msgBody.getSign())) {
            throw new RuntimeException("消息内容签名不一致:" + sign.get());
        }

        return msgBody;
    }


        /**
         * 解析消息，获取业务数据
         * @param msgBody
         * @param clazz
         * @param <T>
         * @return
         */
    public <T> T getData(MessageBody msgBody, Class<T> clazz) {
        T data = JsonUtil.fromJson(JsonUtil.toJsonString(msgBody.getData()), clazz);
        return data;
    }
}
